export const drawText = (
  ctx: CanvasRenderingContext2D,
  canvas: HTMLCanvasElement,
  text: string,
  x: number | "middle",
  y: number,
  size: number,
  color = "#000"
) => {
  // console.log("开始绘制文字--------" + text)
  ctx.font = `${size}px 黑体 bold`
  ctx.fillStyle = color
  if (x === "middle") {
    const textWidth = ctx.measureText(text).width
    const canvasWidth = canvas!.width
    const xPosition = canvasWidth / 2 - textWidth / 2
    ctx.fillText(text, xPosition, y)
  } else {
    ctx.fillText(text, x, y)
  }
  // console.log("结束绘制文字--------")
}

export const drawImage = (ctx: CanvasRenderingContext2D, imageUrl: string, x: number, y: number) => {
  console.log("开始绘制图片--------")
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.src = imageUrl
    image.setAttribute("crossOrigin", "Anonymous")
    image.onload = () => {
      ctx.drawImage(image, x, y, 350, 534)
      resolve(true)
      console.log("结束绘制图片--------")
    }
    image.onerror = () => {
      reject(false)
    }
  })
}

export const drawBackground = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement, imageUrl: string) => {
  // console.log("开始绘制背景--------")
  if (!ctx) return
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.src = imageUrl
    image.onload = () => {
      if (canvas) {
        canvas.width = image.width
        canvas.height = image.height
      }
      ctx.drawImage(image, 0, 0)
      // console.log("结束绘制背景--------")
      resolve(true)
    }
    image.onerror = () => {
      reject(false)
    }
  })
}
